import store from '@/store'
import {
	ENV
} from '@/utils'

const HTTP_ERROR = {
	404: '系统错误,资源未被服务器找到',
	500: '服务器内部错误',
	502: '服务器繁忙，请稍后重试',
	504: '服务器繁忙，请稍后重试'
}


const checkHttpStatus = (response) => {
	if (response.statusCode == 200) {
		let code = Number(response.header.code) || response.statusCode
		let msg = response.data.msg || null
		return {
			...response.data,
			code,
			msg: msg != null ? msg : HTTP_ERROR[response.statusCode]
		}
	} else {
		let code = Number(response.header.code) || response.statusCode
		let msg = response.data.msg || null
		return {
			code,
			msg: msg != null ? msg : HTTP_ERROR[response.statusCode]
		}
	}
}

const checkHttpStatus1 = (response) => {
	let data = JSON.parse(response.data)
	if (response.statusCode == 200) {
		let code = Number(response.header.code) || response.statusCode
		let msg = data.msg || null
		return {
			...data,
			code,
			msg: msg != null ? msg : HTTP_ERROR[response.statusCode]
		}
	} else {
		let code = Number(response.header.code) || response.statusCode
		let msg = data.msg || null
		return {
			code,
			msg: msg != null ? msg : HTTP_ERROR[response.statusCode]
		}
	}
}

export default class HttpUtils {

	/**
	 * GET 网络请求
	 * @param url 请求URL
	 * @param params 请求参数
	 * @param header 额外请求头参数
	 * @param show 是否显示loading
	 * @param errShow 错误提示
	 * @param showLoadingTitle loading描述
	 * @param other 其他域名
	 * @param interfaceTitle 接口名称
	 */
	getRequest({
		url,
		params = {},
		header = {},
		show = true,
		showLoadingTitle = '加载中...',
		other = '',
		interfaceTitle = '',
		errShow = true
	}) {
		return new Promise((resolve, reject) => {
			this._request(resolve, reject, url, params, 'GET', header, show, showLoadingTitle, other,
				interfaceTitle, errShow)
		})
	}

	/**
	 * POST 网络请求
	 * @param url 请求URL
	 * @param params 请求参数
	 * @param header 额外请求头参数
	 * @param show 是否显示loading
	 * @param errShow 错误提示
	 * @param showLoadingTitle loading描述
	 * @param other 其他域名
	 * @param interfaceTitle 接口名称
	 */
	postRequest({
		url,
		params = {},
		header = {},
		show = true,
		showLoadingTitle = '加载中...',
		other = '',
		interfaceTitle = '',
		errShow = true
	}) {
		return new Promise((resolve, reject) => {
			this._request(resolve, reject, url, params, 'POST', header, show, showLoadingTitle, other,
				interfaceTitle, errShow)
		})
	}
	/**
	 * 上传图片 网络请求
	 * @param url 请求URL
	 * @param params 请求参数
	 * @param header 额外请求头参数
	 * @param show 是否显示loading
	 * @param showLoadingTitle loading描述
	 * @param interfaceTitle 接口名称
	 */
	fileRequest({
		url,
		params = {},
		header = {},
		show = true,
		showLoadingTitle = '正在上传...',
		interfaceTitle = ''
	}) {
		return new Promise((resolve, reject) => {
			this._requestFile(resolve, reject, url, params, header, show, showLoadingTitle, interfaceTitle)
		})
	}

	_request(resolve, reject, url, params, method, header, show, showLoadingTitle, other, interfaceTitle, errShow) {
		const _header = {
			'Content-type': "application/json;charset=utf-8",
			'token': store.state.token,
		}
		show && uni.showLoading({
			title: showLoadingTitle,
			mask: true
		})
		uni.request({
			url: other ? other + url : ENV.domainName + url,
			data: params,
			method: method,
			header: {
				..._header,
				...header
			},
			success: (result) => {
				show && uni.hideLoading()
				const _data = checkHttpStatus(result)
				console.log(`********** ${interfaceTitle} **********`)
				console.log({
					接口: url,
					参数: JSON.stringify(params),
					token: store.state.token,
				});
				console.log(interfaceTitle + '：', _data);
				if (Number(_data.code) == 10002) {
					uni.$emit('z-paging-error-emit')
					uni.showToast({
						title: '登录已过期,请重新登录',
						icon: "none",
						mask: true
					})
					uni.reLaunch({
						url: '/pages/loginAccredit/index'
					})
					store.commit('removeUserInfo')
					return true
				}
				if (Number(_data.code) !== 10000 && Number(_data.code) !== 200) {
					uni.$emit('z-paging-error-emit')
					setTimeout(() => {
						errShow && uni.showToast({
							title: _data.msg || '服务器内部错误',
							icon: "none",
							mask: true
						})
					}, 500);
					return reject(_data)
				}
				return resolve(_data)
			},
			fail: (error) => {
				console.log('error', error);
				show && uni.hideLoading()
				if (error.errMsg == 'TypeError: Network request failed') {
					uni.showToast({
						title: '请检查您的网络设置',
						icon: 'none',
						mask: true
					})
				} else if (error.errMsg === "请求超时") {
					uni.showToast({
						title: '服务器繁忙，请您稍后重试',
						icon: 'none',
						mask: true
					})
				} else if (error.errMsg === 'request:fail') {
					uni.showToast({
						title: '拒绝连接',
						icon: 'none',
						mask: true
					})
				} else {
					return reject(error)
				}
			}
		})
	}

	_requestFile(resolve, reject, url, params, header, show, showLoadingTitle, interfaceTitle) {
		show && uni.showLoading({
			title: showLoadingTitle,
			mask: true
		})
		uni.uploadFile({
			url: ENV.domainName + url,
			filePath: params.file,
			name: 'file',
			header: header,
			success: result => {
				show && uni.hideLoading()
				const _data = checkHttpStatus1(result)
				console.log(`********** ${interfaceTitle} **********`)
				console.log({
					接口: url,
					参数: JSON.stringify(params),
					token: store.state.token,
				});
				console.log(interfaceTitle + '：', _data);
				if (Number(_data.code) == 10002) {
					uni.showToast({
						title: '登录已过期,请重新登录',
						icon: "none"
					})
					uni.reLaunch({
						url: '/pages/loginAccredit/index'
					})
					return true
				}
				if (Number(_data.code) !== 10000) {
					setTimeout(() => {
						uni.showToast({
							title: _data.msg || '服务器内部错误',
							icon: "none"
						})
					}, 500);
				}
				return resolve(_data)
			},
			fail: (error) => {
				console.log('error', error);
				show && uni.hideLoading()
				if (error.errMsg == 'TypeError: Network request failed' || error.errMsg ==
					'request:fail -105:net::ERR_NAME_NOT_RESOLVED') {
					setTimeout(() => {
						uni.showToast({
							title: '您的网络不稳定，请检查网络设置或稍后再试',
							icon: 'none',
							mask: true
						})
					}, 500);
				} else if (error.errMsg === "请求超时") {
					setTimeout(() => {
						uni.showToast({
							title: '服务器繁忙，请您稍后重试',
							icon: 'none',
							mask: true
						})
					}, 500);
				} else {
					setTimeout(() => {
						uni.showToast({
							title: '服务器繁忙，请您稍后重试',
							icon: 'none',
							mask: true
						})
					}, 500);
				}
				return reject(error)
			}
		});
	}
}